/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package researchgrants.personalize;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import researchgrants.parts.GrantRequest.grantOfficer.GrantOfficer;

/**
 * This class is used to read and write the configuration in each computer using the program
 * The class also describe the default values, in case the configuration file is not found on a computer.
 * Right now, it support the last logged-in user and the location of the database.
 * @author DOStudent1
 */
public class PropertyFile {

    static PropertyFile loggedIn=null;
    
    // A singleton - So that this instance will be the only one that read and write to the file
    public static PropertyFile getInstance() {
        if (loggedIn==null) {
            loggedIn=new PropertyFile();
        }
        return(loggedIn);
    }

//    private final String propertyFileName="%HOMEPATH%" + File.separator + "properties.cfg";
    private final String propertyFileName="properties.cfg";

    private final String LoggedInGrantOfficerKey="LoggedInGrantOfficer";
    private final String DbFileNameKey="DbFileName";
    
    Properties properties = new Properties();
     private PropertyFile() {
        
        // the default personalized values
        // So if they are not in the file, the have been previously populated with the default values
        properties.put(LoggedInGrantOfficerKey, "");
        properties.put(DbFileNameKey, "src/researchgrants/resources/externals/Research.mdb");
        
        try {
                properties.load(new FileInputStream(propertyFileName));
        } catch (IOException e) {
        }
        
        
    }

    public synchronized String getDbFileName() {
        return((String)properties.get(DbFileNameKey));
    }
    
    // sets the default logged in grant officer.
    // send null to reset the logged in grant officer.
    public synchronized void setLoggedInGrantOfficer(GrantOfficer newLoggedIn) {
        if (newLoggedIn==null) {
            properties.put(LoggedInGrantOfficerKey, "");
        } else {
            properties.put(LoggedInGrantOfficerKey, newLoggedIn.toLoggedData());
        }
        savePropertyFile();
    }
    
    // returns null if not previously set
    public synchronized GrantOfficer getLoggedInGrantOfficer() {
        if (!properties.get(LoggedInGrantOfficerKey).equals("")) {
            return(GrantOfficer.fromLoggedData((String)properties.get(LoggedInGrantOfficerKey)));
        } else {
            return(null);
        }
    }

    private synchronized void savePropertyFile() {
        try {
                properties.store(new FileOutputStream(propertyFileName), null);
        } catch (IOException e) {
            throw new RuntimeException("Could not save personalized data: " + propertyFileName);
        }
    }
}
